<template>
  <!-- 新增按钮 -->
  <el-button type="primary" @click="openSpecialVisible('add')"
    >新增专题</el-button
  >

  <!-- 专题卡片 -->
  <el-row :gutter="10">
    <el-col :span="14">
      <el-card class="card-left">
        <template #header>
          <div>
            <span>专题</span>
          </div>
        </template>
        <!-- 数据表格 -->
        <el-table
          class="dataTable"
          ref="dataTableRef"
          :data="specialList"
          stripe
          highlight-current-row
          :border="true"
          row-key="categoryId"
          style="width: 100%"
          @row-click="rowClick"
        >
          <el-table-column label="#" width="36" type="index" />
          <el-table-column prop="cover" label="封面" width="100">
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <el-image
                  style="width: 80px; height: 80px"
                  fit="fill"
                  :src="proxy.imageUrl + scope.row.cover"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="专题信息" min-width="150">
            <template #default="scope">
              <div class="blogInfo">
                <span>名称:{{ scope.row.categoryName }}</span>
                <span>作者:{{ scope.row.nickName }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="nickDesc" label="简介" min-width="200">
            <template #default="scope">
              <div class="blogInfo">
                <span>{{ scope.row.categoryDesc }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="blogCount" label="博客数量" width="82" />
          <el-table-column label="操作" width="134">
            <template #default="scope">
              <el-button
                type="primary"
                plain
                @click="openSpecialVisible('edit', scope.row)"
              >
                <Edit style="width: 1em; height: 1em" />
              </el-button>
              <el-divider direction="vertical" />
              <el-button type="danger" plain @click="deleteSpecial(scope.row)">
                <Delete style="width: 1em; height: 1em" />
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
          class="pagination"
          :current-page="pageInfo.pageNo"
          :page-size="pageInfo.pageSize"
          :page-sizes="[5, 10, 15]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageInfo.totalCount"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-card>
    </el-col>
    <el-col :span="10">
      <el-card class="card-right">
        <template #header>
          <div>
            <span>专题文章</span>
          </div>
        </template>
        <!-- 提示 -->
        <div :style="{ 'margin-bottom': '5px' }">
          <el-alert
            title="红色代表草稿，绿色代表已发布、拖动文章修改排序"
            type="info"
            show-icon
            :closable="false"
          />
        </div>
        <!-- 数据 -->
        <el-tree
          class="tree"
          ref="treeRef"
          :data="specialArticleData"
          node-key="blogId"
          :expand-on-click-node="false"
          :props="treeProps"
          highlight-current
          default-expand-all
          draggable
          @node-drop="blogDrag"
        >
          <template #default="{ data }">
            <span class="custom-node-style">
              <span>
                <span
                  v-if="data.status == 0"
                  :style="{ color: 'red', 'font-size': '13px' }"
                >
                  {{ data.title }}</span
                >
                <span v-else :style="{ color: 'green', 'font-size': '13px' }">
                  {{ data.title }}</span
                >
              </span>
              <span>
                <template v-if="data.blogId === '0'">
                  <el-button
                    size="small"
                    type="primary"
                    @click="openEditWindow('add', data)"
                    >新增文章</el-button
                  >
                </template>
                <template v-else>
                  <el-button
                    size="small"
                    type="primary"
                    plain
                    @click="openEditWindow('edit', data)"
                  >
                    <Edit style="width: 1em; height: 1em" />
                  </el-button>
                  <el-divider direction="vertical" />
                  <el-button
                    size="small"
                    type="danger"
                    plain
                    @click="deleteBlog(data)"
                  >
                    <Delete style="width: 1em; height: 1em" />
                  </el-button>
                  <el-divider direction="vertical" />
                  <el-button
                    size="small"
                    type="warning"
                    plain
                    @click="openPreviewWindow(data)"
                  >
                    <ZoomIn style="width: 1em; height: 1em" />
                  </el-button>
                  <el-divider direction="vertical" />
                  <el-button
                    size="small"
                    type="primary"
                    @click="openEditWindow('add', data)"
                    >新增下级文章</el-button
                  >
                </template>
              </span>
            </span>
          </template>
        </el-tree>
      </el-card>
    </el-col>
  </el-row>

  <!-- 新增、修改专题窗口 -->
  <el-dialog
    v-model="editFormConfig.show"
    :title="editFormConfig.title"
    @closed="closedEditForm"
    draggable
  >
    <el-form
      :model="editForm"
      label-position="top"
      :rules="editFormRules"
      ref="editFormRef"
    >
      <el-form-item label="名称" prop="categoryName">
        <el-input v-model="editForm.categoryName" />
      </el-form-item>
      <el-form-item label="简介" prop="categoryDesc">
        <el-input
          type="textarea"
          rows="3"
          :autosize="{ minRows: 2, maxRows: 4 }"
          v-model="editForm.categoryDesc"
        />
      </el-form-item>
      <el-form-item label="封面" prop="cover">
        <CoverUpload v-model="editForm.cover"></CoverUpload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span>
        <el-button @click="editFormConfig.show = false">取消</el-button>
        <el-button type="primary" @click="editSpecialSubmit"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 新增、修改博客窗口 -->
  <BlogEdit
    v-show="openCloseEditWindow"
    ref="blogEditRef"
    @close="closeEditWindow"
  ></BlogEdit>

  <!-- 预览窗口 -->
  <BlogPreview
    v-show="openClosePreviewWindow"
    ref="blogPreviewRef"
    @close="closePreviewWindow"
  ></BlogPreview>
</template>

<script setup>
import {
  reactive,
  ref,
  getCurrentInstance,
  onMounted,
  nextTick,
} from "vue";
import BlogEdit from "./BlogEdit.vue";
import BlogPreview from "./BlogPreview.vue";
const { proxy } = getCurrentInstance();

// 部署前执行
onMounted(() => {
  getSpecialList();
});

// 专题列表
const specialList = ref([]);
// 获取专题数据列表
const getSpecialList = async () => {
  let params = {
    pageNo: pageInfo.pageNo,
    pageSize: pageInfo.pageSize,
  };
  let result = await proxy.Request({
    url: "/category/loadCategory4Special",
    params,
  });
  if (!result) {
    proxy.$message.error("获取专题列表失败");
    return;
  }
  specialList.value = result.data.list;
  pageInfo.pageNo = result.data.pageNo;
  pageInfo.pageSize = result.data.pageSize;
  pageInfo.totalCount = result.data.totalCount;
  // 默认选中第一个
  if (currentCategoryId.value == null && result.data.list.length > 0) {
    currentCategoryId.value = result.data.list[0].categoryId;
    getSpecialArticleData();
    nextTick(()=>{
      proxy.$refs.dataTableRef.setCurrentRow(proxy.$refs.dataTableRef.data[0])
    })
  }
};
// 专题表单卡片相关
// 配置
let editFormConfig = reactive({
  show: false,
  title: "新增专题",
});
// 专题表单
const editForm = ref({});
// 表单规则
const editFormRules = {
  categoryName: [{ required: true, message: "请输入分类名称" }],
};
// 打开表单
const openSpecialVisible = (type, data) => {
  editFormConfig.show = true;
  nextTick(() => {
    proxy.$refs.editFormRef.resetFields();
    if (type == "add") {
      editFormConfig.title = "新增专题";
    } else {
      editFormConfig.title = "修改专题";
      editForm.value = JSON.parse(JSON.stringify(data));
    }
  });
};
// 关闭表单
const closedEditForm = () => {
  proxy.$refs.editFormRef.resetFields();
  editForm.value.categoryId = undefined;
};
// 提交表单
const editSpecialSubmit = () => {
  proxy.$refs.editFormRef.validate(async (valid) => {
    if (!valid) {
      proxy.$message.error("请输入分类名称");
      return;
    }
    let params = {};
    Object.assign(params, editForm.value);
    let result = await proxy.Request({
      url: "/category/saveCategory4Special",
      params,
    });
    if (!result) {
      proxy.$message.error(`${editFormConfig.title}失败`);
      return;
    }
    proxy.$message.success(`${editFormConfig.title}成功`);
    editFormConfig.show = false;
    getSpecialList();
  });
};
// 删除专题
const deleteSpecial = (data) => {
  proxy.$messageBox
    .confirm("确认删除吗？", "删除专题", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
    .then(async () => {
      let result = await proxy.Request({
        url: "/category/delCategory4Special",
        params: {
          categoryId: data.categoryId,
        },
      });
      if (!result) {
        proxy.$message.error("删除失败");
        return;
      }
      proxy.$message.success("删除成功");
      specialArticleData.value = null;
      currentCategoryId.value = null;
      getSpecialList();
    })
    .catch(() => {
      proxy.$message.info("取消删除");
      return;
    });
};

// 分页相关
// 分页数据
const pageInfo = reactive({
  pageNo: 1,
  pageSize: 15,
  totalCount: 0,
});
// 页容量改变
const handleSizeChange = (val) => {
  pageInfo.pageSize = val;
  getSpecialList();
};
// 页码改变
const handleCurrentChange = (val) => {
  pageInfo.pageNo = val;
  getSpecialList();
};

// 选择专题，获取其id
let currentCategoryId = ref();
const rowClick = (row) => {
  currentCategoryId.value = row.categoryId;
  getSpecialArticleData();
};

// 专题文章相关
// 专题文章数据
const specialArticleData = ref([]);
// 数据搜索
const getSpecialArticleData = async () => {
  let result = await proxy.Request({
    url: "blog/getSpecialInfo",
    params: {
      categoryId: currentCategoryId.value,
      showType: "1",
    },
  });
  if (!result) {
    proxy.$message.error("获取专题文章失败");
    return;
  }
  specialArticleData.value = result.data;
};
// 树形控件配置
const treeProps = {
  label: "title",
  children: "children",
};
// 节点拖动
const blogDrag = async(before, after, inner, event) => {
  // 节点ID
  const blogId=before.data.blogId
  const pBlogId=after.data.blogId
  // 拖入节点
  let parentNode=null
  if(inner=='inner'){
    parentNode=after
  }else{
    parentNode = after.parent
  }
  // 博客ID重新排序
  const blogIds=[]
  parentNode.childNodes.forEach((element)=>{
    blogIds.push(element.data.blogId)
  })
  let params={
    blogId,
    pBlogId,
    blogIds:blogIds.join(',')
  }
  // 发送请求
  let result = await proxy.Request({
    url:"blog/updateSpecialBlogSort",
    params
  })
  if(!result){
    proxy.$message.error("排序失败")
    return
  }
  proxy.$message.success("重新排序成功")
  getSpecialArticleData()
};

// 编辑弹窗相关
// 编辑弹窗控制
let openCloseEditWindow = ref(false);
let openClosePreviewWindow = ref(false);
// 打开编辑弹窗
const openEditWindow = (type, data) => {
  proxy.$refs.blogEditRef.init(type, data);
  openCloseEditWindow.value = true;
};
const openPreviewWindow = (data) => {
  proxy.$refs.blogPreviewRef.getDetail(data.blogId);
  openClosePreviewWindow.value = true;
};

// 关闭弹窗
const closeEditWindow = () => {
  openCloseEditWindow.value = false;
  getSpecialArticleData();
  getSpecialList()
};
const closePreviewWindow = () => {
  openClosePreviewWindow.value = false;
  getSpecialArticleData();
};

// 删除博客
const deleteBlog = (data) => {
  proxy.$messageBox
    .confirm("确认删除吗？删除内容会移动到回收站！", "删除博客", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
    .then(async () => {
      let result = await proxy.Request({
        url: "/blog/recoveryBlog",
        params: {
          blogId: data.blogId,
        },
      });
      if (!result) {
        proxy.$message.error("删除失败");
        return;
      }
      proxy.$message.success("删除成功");
      getSpecialArticleData();
      getSpecialList()
    })
    .catch(() => {
      proxy.$message.info("取消删除");
      return;
    });
};
</script>

<style lang="scss" scoped>
.card-left {
  margin-top: 10px;

  .dataTable {
    margin-top: 10px;
    height: calc(100vh - 350px);

    .blogInfo {
      display: flex;
      flex-direction: column;

      span {
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
      }
    }
  }
  .pagination {
    margin-top: 10px;
  }
}

.card-right {
  margin-top: 10px;

  .tree {
    height: calc(100vh - 340px);

    .custom-node-style {
      display: flex;
      width: 100%;
      align-items: center;
      justify-content: space-between;
    }
  }
}
</style>